﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WCFServiceWebRole1
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using ChatData;
    /// <summary>
    /// Reads and Writes UserStore collections to and from disk
    /// </summary>
    public class XML
    {
        public static void Write(UserStore<StoreRecord> items, string filename)
        {
            using (XmlTextWriter writer = new XmlTextWriter(filename, Encoding.Default))
            {
                try
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Users");
                    foreach (KeyValuePair<String, StoreRecord> entry in items)
                    {
                        StoreRecord temp = entry.Value;
                        writer.WriteStartElement("User");
                        writer.WriteElementString("Username", temp.Username);
                        writer.WriteElementString("Password", temp.Password);
                        writer.WriteElementString("IP", temp.Ip);
                        writer.WriteElementString("Port", temp.Port.ToString());
                        writer.WriteEndElement();
                    }
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
        public static UserStore<StoreRecord> Read(string filename)
        {
            if (System.IO.File.Exists(filename) != true)
            {
                return null;
            }
            UserStore<StoreRecord> theusers = new UserStore<StoreRecord>();
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(filename);

                XmlNodeList thelist = doc.SelectNodes("//User");
                

                foreach (XmlNode node in thelist)
                {
                    StoreRecord temp = new StoreRecord();
                    temp.Username = node.ChildNodes[0].InnerText;
                    temp.Password = node.ChildNodes[1].InnerText;
                    temp.Ip = node.ChildNodes[2].InnerText;
                    temp.Port = int.Parse(node.ChildNodes[3].InnerText);
                    theusers.Add(temp);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("Empty File");
            }
            return theusers;
        }
    }
}

